package edu.rit.drh4818.file;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


/**
 * Converter to convert UNC datasets to usable form.
 * 
 * http://education.siggraph.org/resources/cgsource/instructional-materials/volume-visualization-data-sets/
 * 
 * @author Darren Headrick
 *
 */
public class UNCDataConverter 
{
	static double windowCenter = 880.0;
	static double windowWidth = 930.0;
	static double windowBase = windowCenter - windowWidth / 2;
	
	public static void main( String[]  args )
	{
		try
		{
			String fileName = "/home/darren/Desktop/mrbrain/MRbrain.new";
			
			int xDim = 256, yDim = 256, zDim = 109;
			int offset = ((256-zDim)/2);
			byte[][][] fileData = new byte[zDim+offset][yDim][xDim];
			
			DataInputStream file = new DataInputStream( new FileInputStream( new File( fileName ) ) );
			DataOutputStream fout = new DataOutputStream( new FileOutputStream( new File( fileName + ".vol" ) ) );
			
			byte[] buffer = new byte[xDim * 2];
		    for (int z = 0; z < zDim; z++) 
		    {
				for (int y = 0; y < yDim; y++) 
				{
				    byte[] dataRow = fileData[z+offset][y];
				    file.readFully(buffer, 0, xDim * 2);
				    for (int x = 0; x < xDim; x++) {
						int index = x * 2;
						// Map the pair of bytes into a short and then window 
						// into a byte
						int low = buffer[index+1];
						if (low < 0) {
						    low += 256;
						}
						int high = buffer[index];
						if (high < 0) {
						    high += 256;
						}
						short fileValue =  (short)((high << 8)  + (low << 0));
						double scaleValue = (fileValue-windowBase)/windowWidth;
						if (scaleValue > 1.0) {
						    scaleValue = 1.0;
						}
						if (scaleValue < 0.0) {
						    scaleValue = 0.0;
						}
						dataRow[x] = (byte)(scaleValue * 255);
				    }
				}
		    }
		    
		    fout.writeInt( 256 );
		    
		    for( int x = 0; x < 256; x++ )
		    {
		    	for( int y = 0; y < 256; y++ )
		    	{
		    		for( int z = 0; z < 256; z++ )
		    		{
		    			if( x >= fileData.length || y >= fileData[x].length || z  >= fileData[x][y].length )
		    			{
		    				fout.writeShort( 0 );
		    			}
		    			else
		    			{
		    				fout.writeShort( fileData[x][y][z] );
		    			}
		    		}
		    	}
		    }
			
		    fout.close();
		    file.close();
		
		}catch( Exception e )
		{
			System.out.println( e );
			e.printStackTrace();
		}
		
	}
	
}
